<template>
  <div class="permission">
    <!-- 面包屑 -->
    <Headline :headline1="$t('m.AccessAdmin')+'  /  '" :headline2="$t('m.PermissionGroupSetting')"></Headline>

    <a-card style="width: 100%">
      <a-alert :message="$t('m.SelectPermissionGroup')" banner closable />
      <div class="search-role">
        <div class="search-new-delete">
          <a-input-search
            class="input-a"
            :placeholder="$t('m.PleaseEnterYourSearchTerms')"
            style="height: 32px width:150px"
            size="large"
            v-model="authfrom.key"
            @search="PerSearch"
          />

          <div class="btns">
            <a-button
              type="primary"
              style="width: 73px; height: 32px"
              @click="addpermiss"
              >{{$t('m.Add')}}</a-button
            >
          </div>
        </div>
      </div>
      <a-table
        style="margin-top: 15px"
        :rowKey="(r, i) => i"
        :columns="columns"
        :data-source="datas"
        bordered
        :pagination="false"
        :row-selection="{
          onChange: perSelectChange,
          type: 'radio',
          selectedRowKeys: setsclete,
        }"
      >
        <div slot="index" slot-scope="text, tag, i">
          {{ i + 1 }}
        </div>
        <div slot="tags" slot-scope="text, tags, i">
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="changed(text, tags, i)"
            >{{$t('m.Examine')}}</a-button
          >
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="editper(text, tags, i)"
            >{{$t('m.Modification')}}</a-button
          >
          <a-button
            class="btn"
            type="danger"
            icon="diff"
            @click="deleteper(text, tags, i)"
            >{{$t('m.Delete')}}</a-button
          >
        </div>
      </a-table>
    </a-card>

    <!-- 新增弹窗 -->
    <Modal :modal="perjust" @modalLast="authOk" @modalhand="perhand">
      <a-form :form="form">
        <a-form-item class="modalItem"
        :label="$t('m.PermissionGroupName')">
        <a-input

          style="width: 300px"
          :placeholder="$t('m.PlaseEnterRoleNumber')"
          v-model="addfroms.groupName"
        />
      </a-form-item>
      <a-form-item class="modalItem" :label="$t('m.periodofvalidity')">
        <a-date-picker
          style="width: 300px"
          v-model="addfroms.endDate"
          @change="endateChange"
        />
      </a-form-item>
      </a-form>
    </Modal>
    <Delete ref="permdelete" :dalete="daletes" @confirm="permdelete"></Delete>

    <!-- 抽屉 -->
    <a-drawer
      title="Basic Drawer"
      placement="right"
      :closable="false"
      :visible="drawer.visible"
      :width="drawer.width"
      @close="onClose"
    >
      <a-card style="width: 100%">
        <a-alert :message="$t('m.OperationsRelatedToPermissionGroupConfiguration')" banner closable />
        <a-row style="margin-top: 15px">
          <a-col :span="10">
            <a-input-search
              class="input-a"
              :placeholder="$t('m.PleaseEnterYourSearchTerms')"
              style="height: 32px width:150px"
              size="large"
              v-model="groupfrom.key"
              @search="sionSearch"
          /></a-col>
          <a-col :span="3">
            <div class="btns">
              <a-button
                type="primary"
                @click="addfacility"
                >{{$t('m.AddingDevice')}}</a-button
              >
            </div>
          </a-col>
        </a-row>
        <a-table
          style="margin-top: 15px; overflow-x: auto"
          :rowKey="(r, i) => r.apgroupid"
          :columns="column"
          :data-source="dataorg"
          bordered
          :pagination="false"
          :row-selection="{
            onChange: perSelectChange,
            type: 'radio',
            selectedRowKeys: setsclete,
          }"
        >
          <div slot="tags" slot-scope="text, tags, i">
            <a class="flex-a" href="#" @click="unitdelete(text, tags, i)"
              >{{$t('m.Delete')}}</a
            >
          </div>
        </a-table>
      </a-card>
    </a-drawer>
    <!-- 新增设备弹窗 -->
    <Modal :modal="perfack" @modalLast="fackOk" @modalhand="fackhand">
      <a-form :form="form">
        <div class="flexs">
        <a-tree-select
          show-search
          style="width: 50%; height: 32px  margin-left: 15px;"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="Please select"
          allow-clear
          @change="checkeds"
          tree-default-expand-all
        >
          <a-tree-select-node
            v-for="item in areatree"
            :key="item.id"
            :cont="item"
            :value="item.areaname"
            :title="item.areaname"
          >
            <a-tree-select-node
              v-for="int in item.children"
              :key="int.id"
              :cont="int"
              :value="int.areaname"
              :title="int.areaname"
            >
              <a-tree-select-node
                v-for="ins in int.children"
                :key="ins.id"
                :cont="ins"
                :value="ins.areaname"
                :title="ins.areaname"
              />
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
        <a-input-search
          class="input-a"
          placeholder="请输入权限组关键词"
          style="height: 32px width:150px ;margin-left: 15px"
          size="large"
          v-model="timelist.key"
          @search="lostSearch"
        />
        <div class="chend">
          <a-checkbox :defaultChecked="timelist.vChild" @change="contChange">
            {{$t('m.WhetherToDisplayChildNodes')}}
          </a-checkbox>
        </div>
      </div>

      <vxe-table
style="margin-top:20px"
          resizable
          :tree-config="{transform: true, rowField: 'id', parentField: 'parentId'}"
          :data="dataroles"
          :checkbox-config="{labelField: 'name', highlight: true}"
          @checkbox-change="selectChangeEvent">
          <vxe-column type="checkbox" :title="$t('m.Door')" width="280" tree-node></vxe-column>
          <vxe-column field="timeInterval" :title="$t('m.Period')"></vxe-column>
          <vxe-column field="weekvalue" :title="$t('m.openDay')"></vxe-column>
          <vxe-column field="machineid" :title="$t('m.deviceNumber')"></vxe-column>
        </vxe-table>
      </a-form>
    </Modal>
    <Delete ref="delete" :dalete="daletes" @confirm="ondelete"></Delete>
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import Modal from "@/components/common/Modal";
import Delete from "@/components/Delete";
import {
  getGroupList,
  getSaveGroup,
  getDelGroup,
  getGroupDevList,
  delGroupDevice,
  getDeviceTimeLists,
  setGroupDevice,
} from "@/api/entrance/entranceguard";
import { getDevAreaTree } from "@/api/perUnit";
import {Setperms} from '@/assets/js/setperms'

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
};

export default {
  name: "PermissionSet",
  components: {
    Headline,
    Modal,
    Delete,
  },
  data() {
    return {
      checkNick: false,
      form: this.$form.createForm(this, { name: 'dynamic_rule' }),
      rowSelection,
      expandedRowKeys: [],
      authfrom: {
        key: "",
        page: 1,
        start: 0,
        limit: 10,
      },
      total: 0,
      drawer: {
        visible: false,
        width: "90%",
      },
      // 配置数据
      columns: [
        {
          title: this.$t('m.PermissionGroupName'),
          dataIndex: "apgroupname",
        },
        {
          title: this.$t('m.periodofvalidity'),
          dataIndex: "enddate",
        },
        {
          title: this.$t('m.Operation'),
          key: "tags",
          // dataIndex: "address",
          scopedSlots: { customRender: "tags" },
        },
      ],
      datas: [],
      columnroles: [
         {
          label: this.$t('m.AnItem'),
          type: "template",
           prop: "",
           align: "center",
        },
        {
          label: this.$t('m.Door'),
          type: "template",

          template: "ones",
           align: "center",
        },
        {
          label: this.$t('m.Period'),
          type: "template",
          template: "isok",
          align: "center",
        },
        {
          label: this.$t('m.openDay'),
          type: "template",
          template: "order",
          align: "center",
        },
        {
          label: this.$t('m.deviceNumber'),
          prop: "doorreadheadid",
        },
      ],
      column: [
        {
          title: this.$t('m.mergingphase'),
          dataIndex: "mergestatus",
          customRender: function (text, record, index) {
            if (text == 0) {
              return "合并中";
            }
          },
        },
        {
          title: this.$t('m.EquipmentName'),
          dataIndex: "devname",
        },
        {
          title: this.$t('m.deviceNumber'),
          dataIndex: "machineid",
        },
        {
          title: this.$t('m.Equipmentserialnumber'),
          dataIndex: "devsn",
        },
        {
          title: this.$t('m.EquipmentArea'),
          dataIndex: "areaname",
        },
        {
          title: this.$t('m.NumberOfGate1Period'),
          dataIndex: "door1",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });
            return arr.join(",");
          },
        },
        {
          title: this.$t('m.NumberOfGate2Period'),
          dataIndex: "door2",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });

            return arr.join(",");
          },
        },
        {
          title: this.$t('m.NumberOfGate3Period'),
          dataIndex: "door3",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });

            return arr.join(",");
          },
        },
        {
          title:  this.$t('m.NumberOfGate4Period'),
          dataIndex: "door4",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });
            return arr.join(",");
          },
        },
        {
          title: this.$t('m.privilegedTime'),
          dataIndex: "createdate",
        },
        {
          title: this.$t('m.Operation'),
          key: "tags",
          // dataIndex: "address",
          scopedSlots: { customRender: "tags" },
        },
      ],
      dataorg: [],
      setsclete: [],
      perjust: {
        visible: false,
        width: "500px",
        title: this.$t('m.AddPermissionGroup'),
      },
      setsclete: [],
      perfack: {
        visible: false,
        width: "900px",
        title: this.$t('m.AddEquipments'),
      },
      addfroms: {
        groupId: "",
        groupName: "",
        endDate: "2050-01-01",
      },
      dalete: {
        titles: this.$t('m.DeleteThePrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToDeleteThisData'),
      },
      daletes: {
        titles: this.$t('m.DeleteThePrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToDeleteThisData'),
      },
      groupId: "",
      groupfrom: {
        groupId: 0,
        key: "",
        start: 0,
        limit: 10,
      },
      anthunitid: {
        ids: "",
        groupId: "",
      },
      areatree: [],
      timelist: {
        key: "",
        areaCode: "",
        vChild: true,
      },
      dataroles: [],
      gourddata: {
        groupId: "",
        devData: [],
      },
      rows: [],
      formation:{
        devData:[],
        groupId:''
      }
    };
  },
  created() {
    this._getGroupList();
    this._getDevAreaTree();
    this._getDeviceTimeLists();
    this.parms = Setperms(this.$route.fullPath,JSON.parse(sessionStorage.getItem('menu')))
    console.log(this.parms)

  },

  methods: {
    isTrue(str){
      return this.parms.indexOf(str) !== -1;
    },
    hhh(row, rowIndex, $event){
            console.log(row, rowIndex, $event)
    },
    getCheckedProp(row, rowIndex, $event){
      console.log(row, rowIndex, $event)
    },
    getCheckedProp(prop,i){
      console.log(prop,i)
    },

    selectChangeEvent ({ records }) {
      let devList = []
      let dataList = []
      records.forEach(item => {
        if(item.children.length !== 0) {
        devList.push(item)
        }
      })
      devList.forEach(citem => {
        let num = []
        for (let index = 0; index < 16; index++) {
          if(index > citem.children.length-1) {
            num.push(0)
          } else {
            num.push(1)
          }
        }
        // devInfo.devId = citem.id
        let doorDemo = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        dataList.push({devId:citem.id,machineId:citem.machineid,
        devSn:citem.devsn,door1:num.join(','),door2:doorDemo,door3:doorDemo,door4:doorDemo})
      })
      this.formation.devData = JSON.stringify(dataList)
      console.log(this.formation)
    },
    _getDevAreaTree() {
      getDevAreaTree().then((res) => {
        this.areatree = res.data;
      });
    },
    _getDeviceTimeLists() {
      getDeviceTimeLists({ params: this.timelist }).then((res) => {

        res.data.forEach(item => {
          item.parentId = null
          for (let index = 0; index < item.children.length; index++) {
            item.children[index]['name'] = '时段方案' + (index+1)

          }
        })

        // res.data.forEach(item => {
        //   for (let index = 0; index < item.children.length; index++) {
        //     item.children[index]['parentId'] = item.id
        //     res.data.push(item.children[index])
        //   }
        // })
        res.data.forEach(item => {
             for (let index = 0; index < item.children.length; index++) {
            item.children[index]['parentId'] = item.id
            res.data.push(item.children[index])
          }
            if(item.starttime) {
            item['timeInterval'] = item.starttime + '-' + item.endtime
          }
        })
        res.data.forEach(item => {
            if(item.starttime) {
            item['timeInterval'] = item.starttime + '-' + item.endtime
          }
        })
        res.data.forEach(item => {
          if(item.weekvalue) {
            let demo = item.weekvalue.split(',')
            let day = []
            for (let index = 0; index < demo.length; index++) {
              if(demo[0] == 1) {
                day.push('周日')
              }
              if(demo[1] == 1) {
                day.push('周一')
              }
              if(demo[2] == 1) {
                day.push('周二')
              }
              if(demo[3] == 1) {
                day.push('周三')
              }
              if(demo[4] == 1) {
                day.push('周四')
              }
              if(demo[5] == 1) {
                day.push('周五')
              }
              if(demo[6] == 1) {
                day.push('周六')
              }
              if(demo[7] == 1) {
                day.push('假日')
              }
              break

            }
            item.weekvalue = day
          }
        })
        console.log(res.data);
        this.dataroles = res.data;
      });
    },
    _getGroupList() {
      getGroupList({ params: this.authfrom }).then((res) => {
        this.datas = res.data.data;
      });
    },
    //搜索
    PerSearch() {
      this._getGroupList();
    },
    //新增
    addpermiss() {
      this.perjust.title = this.$t('m.AddPermissionGroup');
      this.perjust.visible = true;
    },
    //确定
    authOk() {
        this.form.validateFields(err => {
        if (!err) {
          console.info('success');
        }
      });
      if(this.addfroms.groupId != ""){
        getSaveGroup(this.addfroms)
        .then((res) => {
          console.log(res);
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success('添加失败');
            this._getGroupList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.perjust.visible = false;
      this.addfroms.groupId = 0;
      this.addfroms.groupName = "";
      this.addfroms.endDate = "2050-01-01";
      this.form.resetFields();


      }
    },
    //取消
    perhand() {
      this.addfroms.groupId = 0;
      this.addfroms.groupName = "";
      this.addfroms.endDate = "2050-01-01";
      this.form.resetFields();
    },
    //请求设备数据
    _getGroupDevList() {
      getGroupDevList({ params: this.groupfrom }).then((res) => {
        this.dataorg = res.data.data;
      });
    },
    //选中事件
    perSelectChange(select, text) {
      console.log(select, text);
      let obj = {};
      obj.devid = text[0].devid;
      obj.machineId = text[0].machineid;
      obj.devSn = text[0].devsn;
      obj.door1 = text[0].door1;
      obj.door2 = text[0].door2;
      obj.door3 = text[0].door3;
      obj.door4 = text[0].door4;
      this.gourddata.devData.push(obj);
      this.setsclete = select;
    },
    //查看
    changed(text, tags, i) {
      this.drawer.visible = true;
      console.log(tags);
      this.formation.groupId = tags.apgroupid
      this.groupfrom.groupId = tags.apgroupid;
      this.anthunitid.groupId = tags.apgroupid;
      this.gourddata.groupId = tags.apgroupid;
      this._getGroupDevList();
    },
    onClose() {
      this.drawer.visible = false;
    },
    //弹窗删除
    unitdelete(text, tags, i) {
      console.log(tags);
      this.anthunitid.ids = tags.devid;
      this.$refs.delete.visible = true;
    },
    //删除确定
    ondelete() {
      delGroupDevice(this.anthunitid)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getGroupDevList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.delete.visible = false;
    },
    //弹窗搜索
    sionSearch() {
      this._getGroupDevList();
    },
    //修改
    editper(text, tags, i) {
      console.log(tags);
      this.perjust.title = this.$t('m.EditPermissionGroup');
      this.perjust.visible = true;
      this.addfroms.groupId = tags.apgroupid;
      this.addfroms.groupName = tags.apgroupname;
    },
    //删除
    deleteper(text, tags, i) {
      this.groupId = tags.apgroupid;
      this.$refs.permdelete.visible = true;
    },
    //删除确定
    permdelete() {
      getDelGroup({ groupId: this.groupId })
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getGroupList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.permdelete.visible = false;
    },
    //新增设备
    addfacility() {
      this.perfack.visible = true;
    },
    //弹窗确定
    fackOk() {
      // this.gourddata.devData = JSON.stringify(this.gourddata.devData);
      setGroupDevice(this.formation).then((res) => {
        if (res.data.success == true) {
            this.$message.success(res.data.msg);
            this._getGroupDevList()
          } else {
            this.$message.warning(res.data.msg);
          }
          this.perfack.visible = false
      });
    },
    //弹窗取消
    fackhand() {},
    //树形组件切换
    checkeds(value, label, extra) {
      console.log(extra.triggerNode);
      //判断是否选中值了
      if (extra.triggerNode) {
        //获取当前选中的对象信息
        const cont = extra.triggerNode.$attrs.cont;
        this.timelist.areaCode = cont.areacode;
        this._getDeviceTimeLists();
      }
    },
    //是否显示子节点
    contChange() {
      this.timelist.vChild = !this.timelist.vChild;
      this._getDeviceTimeLists();
    },
    lostSearch() {
      this._getDeviceTimeLists();
    },
    chend(end) {
      this.gourddata.devData.push(end);
    },
    //tree表格方法
    // rowSelection(){},
    //处理时间格式
    endateChange(date, dateString) {
      this.addfroms.endDate = dateString;
    },
  },
};
</script>

<style scoped lang="scss">
.search-a {
  width: 800px;
  height: 32px;
}
.ov_flex {
  display: flex;
  align-items: center;
}
#components-table-demo-size {
  margin-top: 15px;
}
.input-a {
  height: 32px;
  font-size: 12px;
  margin-right: 15px;
}
/deep/ .ant-input {
  height: 32px;
  font-size: 13px;
}
.chend {
  width: 300px;
  margin-left: 15px;
}
.logflex {
  display: flex;
}
.flex-a {
  margin-left: 5px;
}
.modalItem {
  display: flex;
  margin-top: 20px;
  justify-content: center;
}
/deep/ .ant-table-tbody > tr > td {
  padding: 16px 10px !important;
}
.search-role {
  width: 100%;
  line-height: 60px;
}

.search-new-delete {
  display: flex;
  width: 400px;
  align-items: center;
}

.flexs {
  display: flex;
  align-items: center;
}
.btn{
  margin-left: 15px;
}
.btns{
  margin-left: 15px;
}
</style>
